<template>
    <canvas ref="captchaCanvas" width="120" height="40" @click="generateCaptcha"
        style="border: 1px solid #dcdfe6; cursor: pointer; margin-left: 80px;"></canvas>
</template>

<script setup>
import { onMounted, ref } from 'vue'
const emit = defineEmits()
// 用于存储当前生成的验证码
let currentCaptcha = ''

// 通过 ref 获取 canvas 元素的引用
const captchaCanvas = ref(null)

// 生成图形验证码
const generateCaptcha = () => {
    const canvas = captchaCanvas.value
    if (!canvas) return
    const ctx = canvas.getContext('2d')

    // 设置字体和背景颜色
    ctx.font = '30px Arial'
    ctx.fillStyle = '#f0f0f0'
    ctx.fillRect(0, 0, canvas.width, canvas.height)  // 清空画布并填充背景

    // 随机生成4位字符
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    currentCaptcha = ''
    for (let i = 0; i < 4; i++) {
        currentCaptcha += chars.charAt(Math.floor(Math.random() * chars.length))
    }

    // 绘制验证码文本
    ctx.fillStyle = '#000000'
    ctx.fillText(currentCaptcha, 20, 30)

    // 添加干扰线
    for (let i = 0; i < 5; i++) {
        ctx.beginPath()
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)'
        ctx.stroke()
    }

    // 添加干扰点
    for (let i = 0; i < 30; i++) {
        ctx.beginPath()
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
        ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
        ctx.fill()
    }
    emit('updateCaptcha', currentCaptcha)
}


// 页面加载时生成验证码
onMounted(() => {
    generateCaptcha()
})
</script>